<template>
	<van-popup v-model:show="showCondition" teleport="#app" position="bottom" class="drawer-bottom" round closeable @closed="onCancel">
		<div class="popup-title">全部筛选</div>
		<div class="main-wrap">
			<van-cell class="mgb20" v-if="locateAble" title="收货地" is-link arrow-direction="down" :value="locateText" @click="showLocatePicker=true"/>
			<van-cell class="mgb20" v-else title="收货地" :value="locateText"/>
			<div class="cell-group">
				<div class="cell-wrap">
					<ul class="item-list">
						<li :class="myCondition.inStork===1? 'active':''" @click="myCondition.inStork= myCondition.inStork===0? 1:0">仅看有货</li>
						<li :class="myCondition.inReplaceGrant===0? 'active':''" @click="myCondition.inReplaceGrant = myCondition.inReplaceGrant===0? 1:0">一件代发</li>
					</ul>
				</div>
			</div>
			<div class="cell-group">
				<div class="cell-title"><van-badge position="top-left" :dot="myCondition.minPrice!==''||myCondition.maxPrice!==''"><label>价格区间(元)</label></van-badge></div>
				<div class="cell-wrap">
					<van-stepper v-model="myCondition.minPrice" integer :min="1" :max="999999999" :show-plus="false" default-value="" placeholder="￥最低价"
								 :show-minus="false" :long-press="false" :allow-empty="true"/> -
					<van-stepper v-model="myCondition.maxPrice" integer :min="myCondition.minPrice" :max="999999999" :show-plus="false" default-value="" placeholder="￥最高价"
								 :show-minus="false" :long-press="false" :allow-empty="true"/>
				</div>
			</div>
			<van-cell class="mgb20" is-link :value="getCatPath" @click="catVisible=true">
				<template #title><van-badge position="top-left" :dot="myCondition.catId!==''"><label>分类</label></van-badge></template>
			</van-cell>
			<div class="cell-group">
				<div class="cell-title">
					<van-badge position="top-left" :dot="myCondition.brandList.length>0"><label>品牌</label></van-badge>
					<div class="right-info" @click="toggleBrandCollapse">{{!brandCollapse? '展开':'收起'}} <van-icon :name="brandCollapse? 'arrow-up':'arrow-down'"/></div>
				</div>
				<div class="cell-wrap">
					<ul class="item-list" :style="'height:'+(!brandCollapse?'84px':'auto')">
						<template v-for="(item,index) in brandOptions" key="index">
							<li v-if="includeItem(myCondition.brandList,item.value)" class="active" @click="removeItemFromList(myCondition.brandList,item.value)">{{item.label}}</li>
							<li v-else @click="addItem2List(myCondition.brandList,item.value)">{{item.label}}</li>
							<template v-if="index===4">
							<li class="more-items" v-show="!brandCollapse" @click="brandCollapse=true">查看更多 <van-icon name="arrow-down"/></li>
							</template>
						</template>
					</ul>
				</div>
			</div>
			<div class="cell-group" v-if="!shopId">
				<div class="cell-title">
					<van-badge position="top-left" :dot="myCondition.shopList.length>0"><label>供货商</label></van-badge>
					<div class="right-info" @click="toggleShopCollapse">{{!shopCollapse? '展开':'收起'}} <van-icon :name="shopCollapse? 'arrow-up':'arrow-down'"/></div>
				</div>
				<div class="cell-wrap">
					<ul class="item-list shop-item" :style="'height:'+(!shopCollapse?'84px':'auto')">
						<template v-for="(item,index) in shopOptions" key="index">
							<li v-if="includeItem(myCondition.shopList,item.value)" class="active" @click="removeItemFromList(myCondition.shopList,item.value)">{{item.label}}</li>
							<li v-else @click="addItem2List(myCondition.shopList,item.value)">{{item.label}}</li>
							<template v-if="index===2">
							<li class="more-items" v-show="!shopCollapse" @click="shopCollapse=true">查看更多 <van-icon name="arrow-down"/></li>
							</template>
						</template>
					</ul>
				</div>
			</div>
		</div>
		<div class="drawer-btn">
			<van-button type="warning" block class="button-first" @click="resetCondition(undefined)">重置</van-button>
			<van-button type="primary" block class="button-last" :color="themeColor? themeColor:'var(--van-primary-color)'" @click="handleSearch">完成</van-button>
		</div>
		<transition name="van-slide-right">
			<div v-show="catVisible" class="category-wrap">
				<div class="cat-already">
					已选： <span class="txt-primary">{{getCatPath}}</span>
				</div>
				<van-collapse v-model="cateColActives" class="cate-list">
					<van-cell title="全部分类" is-link @click="setNewCatId('')">
						<template #right-icon>
							<van-icon v-if="''!==myCondition.catId" name="circle"/><van-icon v-else name="checked" class="txt-primary"/>
						</template>
					</van-cell>
					<template v-for="(first,i1) in category" key="i1">
						<van-cell v-if="!first.children" :title="first.label" is-link @click="setNewCatId(first.id)">
							<template #right-icon>
								<van-icon v-if="first.id!==myCondition.catId" name="circle"/><van-icon v-else name="checked" class="txt-primary"/>
							</template>
						</van-cell>
						<van-collapse-item v-else :title="first.label" :name="first.id">
							<van-cell title=" -- 全部" is-link @click="setNewCatId(first.id)">
								<template #right-icon>
									<van-icon v-if="first.id!==myCondition.catId" name="circle"/><van-icon v-else name="checked" class="txt-primary"/>
								</template>
							</van-cell>
							<van-cell v-for="(item,i2) in first.children" key="i2" :title="' -- '+item.label" is-link @click="setNewCatId(item.id)">
								<template #right-icon>
									<van-icon v-if="item.id!==myCondition.catId" name="circle"/><van-icon v-else name="checked" class="txt-primary"/>
								</template>
							</van-cell>
						</van-collapse-item>
					</template>
				</van-collapse>
				<div class="drawer-btn"><van-button block round @click="catVisible=false">取消</van-button></div>
			</div>
		</transition>
	</van-popup>
	<van-popup v-if="locateAble" v-model:show="showLocatePicker" round position="bottom">
		<van-picker :columns="locateColumns" @cancel="showLocatePicker = false" @confirm="onLocateConfirm" title="选择我的收货地" />
	</van-popup>
</template>
<style lang="scss" scoped>
.popup-title{height:48px;display:flex;align-items:center; justify-content: center}
.main-wrap{
	height:calc(84vh - 98px);
	:deep(.van-cell__title){flex:0.25;font-size:15px}
	.cell-group{
		position:relative;
		margin-bottom:10px;
		&::after{
			position: absolute;
			box-sizing: border-box;
			content: " ";
			pointer-events: none;
			right: var(--van-padding-md);
			bottom: 0;
			left: var(--van-padding-md);
			border-bottom: 1px solid var(--van-cell-border-color);
			transform: scaleY(.5);
		}
		.cell-title{
			color:var(--font-first-color);padding:10px 16px;font-size: 15px;
			display:flex;align-items: center;justify-content:space-between;
			.right-info{color:var(--font-third-color);font-size:12px;}
		}
		.cell-wrap{
			padding:0 16px 10px 16px;
		}
		:deep(.van-stepper__input){
			border-radius:16px; width:42vw; height:32px;
			&::placeholder{color:var(--font-disable-color);}
		}
		.item-list{
			margin:0 -10px -10px 0;display:flex;padding:0; flex-wrap:wrap; overflow:hidden;
			&>li{
				display:block; text-align:center; line-height:30px; width:calc((100vw - 52px)/3);
				//max-width:calc(50vw - 20px);
				overflow: hidden; white-space: nowrap; text-overflow: ellipsis; position:relative; color:var(--font-second-color);
				margin:0 10px 10px 0;padding:0 10px;height:32px;border-radius:20px; font-size:13px;
				border:1px solid var(--bar-input-color);

				&::before{
					width:100%;height:100%; top:0;left:0;position:absolute;content:" ";
					background-color:var(--bar-input-color);z-index:-1;
				}
				&.active{
					border-color:var(--van-primary-color);color:var(--van-primary-color);
					&::before{
						background-color:var(--van-primary-color); opacity: .1;
					}
				}
				&.more-items{
					border-color:var(--border-color);
				}
			}
			&.shop-item>li{
				width:calc(50vw - 21px);
			}
		}
	}
}
.category-wrap{
	--van-collapse-item-content-padding:0;
	height:calc(84vh);width:100%; position:absolute;bottom:0;left:0;z-index:2;
	overflow-x:hidden; overflow-y:auto; background-color:var(--white-color);
	.cat-already{padding:10px 16px;display:flex;align-items: center;height:45px; font-size:14px; border-bottom:1px solid var(--border-lighter-color)}
	.cate-list{
		height:calc(84vh - 95px); overflow-x:hidden;overflow-y:auto;margin-bottom:50px
	}
	:deep(.van-cell){padding:8px 16px;}
	:deep(.van-cell__title){flex:5}
	.van-icon{font-size:20px; line-height: inherit; color:var(--font-third-color); }
	:deep(.van-hairline--top-bottom:after){border-width:0}
}
</style>
<script lang="ts" setup generic="T">
import { SearchGoodsCondition } from '@/types'
import {lengthCutting} from "@/utils/validate";
//搜索商品查询条件

//props
const props=defineProps({
	themeColor:{
		type:String,
		required:false,
	},
	shopId:{
		type:String,
		required:false,
	},
	locateAble:{
		type:Boolean,
		required:false,
	}
})

//emits
const emits = defineEmits(['handleSearch'])

//data
const showCondition=ref(false)
const myCondition = reactive(<SearchGoodsCondition>{
	inStork:1,          //是否有货
	inReplaceGrant:0,   //是否一件代发
	//innerKey:string,           //内部继续搜索用的关键字
	locate:'9A-',            //todo:收货地区编码，来自于用户配置的收货地址区域 重置时，应从用户的收货地列表中选择默认的第一个地址的省市
	minPrice:0,            //价格区间最低
	maxPrice:0,            //价格区间最高
	shopId:props.shopId? props.shopId:undefined,
	shopList:[],
	brandList:[],
	catId:'',
})
//Object.assign(myCondition, props.condition)   //setup时，先把入参覆盖内部响应数据
												//每次打开时，都需要重新传入以选的查询排序条件，重新覆盖内部响应数据。以重新渲染筛选面板的显示
												//以确保用户在更改条件后又取消了刚才的更改后，下次打开时，仍然保留更新前的显示
//定位相关data
const showLocatePicker=ref(false)  //如果不是渠道，则不提供收货地选择
const locateColumns=[// todo: 通过用户类型、用户信息读取可选的地址信息
	{ text: '北京 - 东城区', value: 'Hangzhou' },
	{ text: '浙江 - 杭州', value: 'Ningbo' },
	{ text: '新疆 - 乌鲁木齐', value: 'Wenzhou' },
	{ text: '广西 - 南宁', value: 'Shaoxing' },
	{ text: '黑龙江 - 齐齐哈尔', value: 'Huzhou' },
]
const locateText=ref('北京 - 东城区')
//品牌表相关data
const brandCollapse=ref(false)
const toggleBrandCollapse=()=>{brandCollapse.value=!brandCollapse.value}
const brandOptions=ref([  //todo: 品牌列表，待选过滤元素，需查询出
	{value:'01',label:'苹果（Apple）'},
	{value:'02',label:'华为（Huawei）'},
	{value:'03',label:'联想（LENOVO）联想（LENOVO）'},
	{value:'04',label:'OPPO'},
	{value:'05',label:'小米（MI）'},
	{value:'06',label:'VIVO'},
	{value:'07',label:'三星'},
	{value:'08',label:'华硕（ASUS）'},
	{value:'09',label:'微星（MSI）'},
	{value:'10',label:'技嘉（Gigabite）'},
])

//供货商相关data
const shopCollapse=ref(false)
const toggleShopCollapse=()=>{shopCollapse.value=!shopCollapse.value}
const shopOptions=ref([  //todo: 供货商列表，待选过滤元素，需查询出
	{value:'ZBCU01',label:'联通华盛旗舰店'},
	{value:'ZBCU02',label:'天猫优选'},
	{value:'ZBCU03',label:'小沃科技旗舰店'},
	{value:'ZBCU04',label:'吉客空间'},
	{value:'ZBCU05',label:'美视博通讯（全国店）'},
	{value:'ZBCU06',label:'泽万家通讯（全国店）'},
	{value:'ZBCU07',label:'森锐直营旗舰店'},
])

//商品类型树相关data
//todo: 定义商品类型树，还需要完成从店铺/全平台的solr中异步读取
//todo: (通过搜索关键字、shopId（可选，店铺查询时用），筛选出的商品中提取这些数据并distinct)
//商品类型树，最多只显示到第二层为止
const category = ref(<Array<any>>[])
category.value = [
	{
		id:'01',label:'手机终端',
		children:[
			{ id:'0101',label:'5G手机', },
			{ id:'0102',label:'4G手机', },
			{ id:'0103',label:'另类手机', },
		]
	},
	{
		id:'02',label:'智慧生活',
		children:[
			{ id:'0201',label:'游戏娱乐', },
			{ id:'0202',label:'智能控制', },
			{ id:'0203',label:'智能固话', },
			{ id:'0204',label:'联通超清',},
			{ id:'0205',label:'联通看家', },
			{ id:'0206',label:'健康护理', },
			{ id:'0207',label:'智能厨电', },
			{ id:'0208',label:'软终端', },
			{ id:'0209',label:'办公设备', },
			{ id:'0210',label:'智能家电', },
			{ id:'0211',label:'安防传感终端', },
			{ id:'0212',label:'联通组网', },
			{ id:'0213',label:'车载出行', },
			{ id:'0214',label:'其他智能终端', },
		]
	},
	{
		id:'03',label:'智慧固网',
		children:[
			{ id:'0301', label:'IPTV机顶盒', },
			{ id:'0302', label:'ONU终端', },
			{ id:'0303', label:'XDSL终端',},
			{ id:'0304', label:'家庭网关', },
			{ id:'0305', label:'其他客户接入类',},
		]
	},
	{
		id:'04',label:'个人智能终端',
		children:[
			{ id:'0401',label:'智能手表', },
			{ id:'0402',label:'智能手环', },
			{ id:'0403',label:'平板电脑', },
			{ id:'0405',label:'智能耳机', },
			{ id:'0406',label:'智能机器人', },
			{ id:'0407',label:'XR终端', },
			{ id:'0408',label:'PC台式机', },
			{ id:'0409',label:'笔记本电脑', },
			{ id:'0410',label:'随身Wifi', },
		]
	},
	{
		id:'06',label:'3C配件',
		children:[
			{ id:'0601',label:'数码配件', },
			{ id:'0602',label:'电脑配件', },
			{ id:'0603',label:'其它配件', },
		]
	},
	{
		id:'10',label: '权益类产品',
	}
]
const cateColActives=ref(<string[]>[]) //商品列表中，那些已经下拉展示的一级节点
const catVisible=ref(false)
const getCatPath=computed(()=>{
	//仅提供两层分类！
	if(myCondition.catId==='')	return '全部分类'
	let strArr = lengthCutting(myCondition.catId,2)
	let strPath=[]
	console.log(strArr)
	for(let firstLevel of category.value){
		if(firstLevel.id===strArr[0]){
			strPath.push(firstLevel.label)
			if(!firstLevel.children)	break
			for(let secLevel of firstLevel.children){
				if(secLevel.id===myCondition.catId){
					strPath.push(secLevel.label)
					break
				}
			}
			break
		}
	}
	return strPath.join(' / ')
})

//methods
const includeItem=(list:Array<any>,val:string)=>{
	return list.includes( val)
}
const removeItemFromList= (list: Array<any>, val: string)=>{
	for(let i=0;i<list.length;++i){
		if(list[i] === val){
			list.splice(i,1)
			break
		}
	}
}
const addItem2List=(list:Array<any>,val:string)=>{
	for(let i=0;i<list.length;++i){
		if(list[i] === val){
			return
		}
	}
	list.push(val)
}
const onLocateConfirm=({selectedOptions}:any)=>{
	showLocatePicker.value = false
	locateText.value = selectedOptions[0].text
	myCondition.locate = selectedOptions[0].value
}
//设置新的商品分类节点
const setNewCatId=(newId:string)=>{
	myCondition.catId=newId
	catVisible.value=false
}

const handleSearch=()=>{
	emits('handleSearch',myCondition)
	console.log('myCondition',myCondition);
	showCondition.value=false
}
const resetCondition=(newObj?:SearchGoodsCondition)=>{
	if(newObj){
		console.log(newObj)
		myCondition.inStork = newObj.inStork
		myCondition.inReplaceGrant = newObj.inReplaceGrant
		myCondition.locate = newObj.locate //todo:收货地区编码，来自于用户配置的收货地址区域 重置时，应从用户的收货地列表中选择默认的第一个地址的省市
		myCondition.minPrice = newObj.minPrice
		myCondition.maxPrice = newObj.maxPrice
		myCondition.shopList.splice(0,myCondition.shopList.length)
		myCondition.brandList.splice(0,myCondition.brandList.length)
		myCondition.shopList.push(...newObj.shopList)
		myCondition.brandList.push(...newObj.brandList)
		myCondition.catId=newObj.catId
	}else{
		myCondition.inStork = true
		myCondition.inReplaceGrant = false
		myCondition.locate = '9A-' //todo:收货地区编码，来自于用户配置的收货地址区域 重置时，应从用户的收货地列表中选择默认的第一个地址的省市
		myCondition.minPrice = ''
		myCondition.maxPrice = ''
		myCondition.shopId = props.shopId? props.shopId:undefined
		myCondition.shopList.splice(0,myCondition.shopList.length)
		myCondition.brandList.splice(0,myCondition.brandList.length)
		myCondition.catId=''
	}

}
const displaySheet=(cond:SearchGoodsCondition)=>{
	showCondition.value=true
	//todo:判断品类、店铺列表、品牌列表是否需要异步载入各选项，以及载入各选项，待载入完全后，再进行渲染
	resetCondition(cond)
}
const onCancel=()=>{
	catVisible.value=false
}

defineExpose({
	displaySheet,handleSearch,resetCondition,
})
</script>